package ms.authority.service;

import ms.authority.bean.UserParamBean;
import ms.authority.config.ResponseCode;
import ms.authority.dao.UserDao;
import ms.authority.entity.User;
import ms.common.exception.BizException;
import ms.common.token.TokenUtil;
import ms.common.util.bean.BeanUtil;
import ms.common.util.string.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Project Name: ms
 * File Name: LoginService
 * Package Name: ms.authority.service
 * Date: 2018/5/9  17:05
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Service
public class LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDao userDao;

    /**
     * 登录
     * @param userParamBean
     * @return
     */
    public Map<String,Object> sign(UserParamBean userParamBean) {
        Map<String,Object> result = new HashMap<>();

        User user = BeanUtil.copy(userParamBean, User.class);
        user.setStatus(1);

        User existUser = userDao.findOneByBean(user, User.class);
        if(StringUtil.isEmpty(existUser)) {
            throw new BizException(ResponseCode.USER_UN_EXIST,"用户信息不存在");
        }

        String token = TokenUtil.createToken(existUser.getId());
        result.put("realName", existUser.getRealName());
        result.put("token", token);
        result.put("permissions", existUser.getPermissions());

        //向缓存中添加数据
        Map<String,Object> users = redisTemplate.opsForHash().entries("ms-authority");
        if(StringUtil.isEmpty(users)) {
            users = new HashMap<>();
        }
        users.put(existUser.getId(), existUser.getUrls());
//        redisTemplate.opsForHash().put("ms-authority", existUser.getId(), existUser.getUrls());
        redisTemplate.opsForHash().putAll("ms-authority", users);
        return result;
    }
}
